package com.liu.user.interceptor;

import com.liu.common.utils.JacksonUtil;
import com.liu.common.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by Administrator on 2019/8/21 0021.
 */
@Component
@Slf4j
public class JwtInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtUtil jwtUtil;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        log.info("进入了权限拦截器{}");
//          这里主要做的是做权限的解析，而不是拦截用户请求
        String header =request.getHeader("Authorization");
        log.info("header{}",StringUtils.isEmpty(header));
        if(!StringUtils.isEmpty(header) && header.startsWith("Bearer ")){
            final String token = header.substring(7);
            try{
                Claims claims = jwtUtil.parseJWT(token);
               log.info("claims{}",JacksonUtil.printJson(claims));
                if(claims!=null){
                    if("admin".equals(claims.get("roles"))){//如果是管理员
                        request.setAttribute("admin_claims", claims);
                    }
                    if("user".equals(claims.get("roles"))){//如果是用户
                        request.setAttribute("user_claims", claims);
                    }
                }
            }catch (Exception e){
                throw new RuntimeException("令牌不正确");
            }
        }

        return true;
    }
}
